package com.inforich.quartz.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.inforich.common.enums.BookingEnum;
import com.inforich.common.utils.DateUtils;
import com.inforich.orderManage.domain.Booking;
import com.inforich.orderManage.domain.Transport;
import com.inforich.orderManage.service.IBookingService;
import com.inforich.orderManage.service.ITransportService;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: 预约单相关定时任务
 * @author: HJM
 * @date: 2022/11/1
 */
@Component("bookingTask")
public class BookingTask {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass());
  private static final String TASK_NAME = "[定时任务-预约单自动结束]";

  @Autowired
  private IBookingService bookingService;
  @Autowired
  private ITransportService transportService;

  /**
   * 超过一天没有新的运输单，则预约单直接结束
   */
  public void autoEnd() {
    // 查询所有进行中的预约单
    Map<String, Object> map = new HashMap<>();
    map.put("state", BookingEnum.CONDUCT.getDbData());
    List<Booking> bookingList = bookingService.listBooking(map);
    if (CollUtil.isEmpty(bookingList)) {
      logger.error(TASK_NAME + "结束，没有进行中的预约单");
      return;
    }
    for (Booking booking : bookingList) {
      // 预约时间是否超过一天
      Date bookingTime = booking.getBookingTime();
      Date now = new Date();
      int diff = DateUtils.differentDaysByMillisecond(bookingTime, now);
      List<Transport> transportList = transportService.listByBookingId(booking.getId());

      if (diff > 0) {
        // 没有运输单已过期
        if (CollUtil.isEmpty(transportList)) {
          bookingService.update(new LambdaUpdateWrapper<Booking>().set(Booking::getState,
              BookingEnum.OVERDUE.getDbData()).eq(Booking::getId, booking.getId()));
        } else {
          // 有输运单且没有正在进行中的运输单
          long count = transportList.stream().filter(t -> t.getEndTime() == null).count();
          if (count == 0) {
            bookingService.update(new LambdaUpdateWrapper<Booking>().set(Booking::getState,
                    BookingEnum.COMPLETE.getDbData()).set(Booking::getCompleteTime, new Date())
                .eq(Booking::getId, booking.getId()));
          }
        }
      }
    }
  }

  public static void main(String[] args) throws ParseException {
    Date date1 = DateUtils.parseDate("2022-11-01 20:00:00", "yyyy-MM-dd HH:mm:ss");
    Date date2 = DateUtils.parseDate("2022-11-02 21:00:59", "yyyy-MM-dd HH:mm:ss");
    System.out.println(date2.getTime() - date1.getTime());
    int diff = DateUtils.differentDaysByMillisecond(date1, date2);
    System.out.println(diff);
  }

}
